package cn.wgx.commons.interceptor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;

@Component
public class FileInterceptor extends HandlerInterceptorAdapter {

    @Value("${upload.file.allowed}")
    private String FILE_ALLOWED = ".jpg|.png|.gif|.jpeg";
    @Value("${upload.file.denied}")
    private String FILE_DENIED = "exe|jsp|asp|jsa";

    private String FILE_ALLOWEDS[];

    private String FILE_DENIEDS[];

    private String ERROR_RESPONSE = "{\"success\":false,\"res\":\"不支持的文件格式\"}";

    @PostConstruct
    public void init(){
        if(FILE_ALLOWED != null){
            FILE_ALLOWEDS = FILE_ALLOWED.split("\\|");
        }else{
            FILE_ALLOWEDS = new String[0];
        }
        if(FILE_DENIED != null){
            FILE_DENIEDS = FILE_DENIED.split("\\|");
        }else{
            FILE_DENIEDS = new String[0];
        }
    }

    /**
     * 检测不能上传的文件后缀
     * @param filename
     * @return true为不能上传的文件
     */
    private boolean checkDeniedFile(String filename) {
        if(null == filename) return false;
        for(String f: FILE_DENIEDS){
            if(filename.endsWith(f))return true;
        }
        return false;
    }


    private boolean checkAllowFile(String filename) {
        if(null == filename) return false;
        for(String f: FILE_ALLOWEDS){
            if(filename.endsWith(f))return true;
        }
        return false;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag = true;
        // 判断是否为文件上传请求
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest =
                    (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> files =
                    multipartRequest.getFileMap();
            Iterator<String> iterator = files.keySet().iterator();
            //对多部件请求资源进行遍历
            while (iterator.hasNext()) {
                String formKey = (String) iterator.next();
                MultipartFile multipartFile =
                        multipartRequest.getFile(formKey);
                String filename = multipartFile.getOriginalFilename();
                //判断是否为限制文件类型
                if (checkDeniedFile(filename)) {
                    flag = false;
//                    JSONObject o = new JSONObject();
//                    o.put("success", false);
//                    o.put("res", "不支持的文件格式.");
                    response.setContentType("application/json;charset=utf-8");
                    PrintWriter w = response.getWriter();
                    w.write(ERROR_RESPONSE);
                    w.close();
                }
            }
        }
        return flag;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }
}
